package com.yy.wga.wechat.service.manager;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.yy.wga.common.core.enmus.EResponseCode;
import com.yy.wga.common.core.exception.BusinessException;
import com.yy.wga.wechat.feign.response.WechatGetAccessTokenResp;
import com.yy.wga.wechat.service.config.WxMaConfiguration;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WechatManager {
    public WxMaJscode2SessionResult getUserSessionInfo(String code) {
        WxMaService wxService = WxMaConfiguration.getMaService();
        try {
            return  wxService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            log.error("微信openId登录失败", e);
            throw new BusinessException("微信登录失败，请退出小程序重试");
        }
    }

    public WxOAuth2AccessToken getOfficialOAuth2AccessToken(String code) {
        WxMpService wxService = WxMaConfiguration.getOfficialAccountService();

        try {
            return wxService.getOAuth2Service().getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("微信openId登录失败", e);
            throw new BusinessException("微信登录失败，请退出小程序重试");
        }
    }

    public WechatGetAccessTokenResp getAccessToken() {
        WxMaService maService = WxMaConfiguration.getMaService();
        WechatGetAccessTokenResp response = new WechatGetAccessTokenResp();
        response.setAppId(maService.getWxMaConfig().getAppid());
        try {
            String token = maService.getAccessToken();
            response.setAccessToken(token);
        } catch (WxErrorException e) {
            log.error("获取token异常", e);
            throw new BusinessException(EResponseCode.SYSTEM_BUSY_ERROR);
        }
        return response;
    }

    public WechatGetAccessTokenResp getChannelAccessToken() {
        WxMaService maService = WxMaConfiguration.getChannelMaService();
        WechatGetAccessTokenResp response = new WechatGetAccessTokenResp();
        response.setAppId(maService.getWxMaConfig().getAppid());
        try {
            String token = maService.getAccessToken();
            response.setAccessToken(token);
        } catch (WxErrorException e) {
            log.error("获取token异常", e);
            throw new BusinessException(EResponseCode.SYSTEM_BUSY_ERROR);
        }
        return response;
    }

    public void sendSubscribeMsg(WxMaSubscribeMessage request) {
        try {
            WxMaConfiguration.getMaService().getMsgService()
                    .sendSubscribeMsg(request);
        } catch (WxErrorException e) {
            log.error("发送订阅消息异常");
        }
    }
}
